<?php
defined('IN_SITE') or exit('Access Denied');

require_once 'tree.class.php';
require_once 'page.class.php';
require_once MOD_ROOT.'content/content.class.php';

$tree = new tree;
$pageid = isset($pageid) ? intval($pageid) : 0;
$cat = new page();
$c = new content();


$action = $action ? $action : 'manage';
if(!$forward) $forward = '?module='.$module.'&action=manage';


// 菜单
$submenu[] = array('<font color="red">发布信息</font>', '?module='.$module.'&action=add&catid='.$catid);
$submenu[] = array('草稿', '?module='.$module.'&action=draft&catid='.$catid);
$submenu[] = array('管理', '?module='.$module.'&action=manage&catid='.$catid);
$submenu[] = array('回收站', '?module='.$module.'&action=recycle&catid='.$catid);
$submenu[] = array('浏览', '?module='.$module.'&action=browse&catid='.$catid);
$menu = admin_menu($CATEGORY[$catid]['catname'].' 栏目管理', $submenu);
	

switch($action)
{
	case 'add':
		if($dosubmit)
		{
		    if(!$page['catname']) showmessage($LANG['page_name_not_null']);
			$page['catname'] = trim($page['catname']);
			$page['catdir'] = trim($page['catdir']);
			$pageid = $cat->add($page, $setting);
			
			//$priv_group->update('pageid', $pageid, $priv_groupid);
			//$priv_role->update('pageid', $pageid, $priv_roleid);
			
			// 请修复栏目
			$cat->repair();
			
			// 更新栏目缓存 （增加）
			cache_common();
			cache_page();
			
			showmessage('操作成功！开始修复栏目数据...', '?module=page&action=repair');
			
		}
		else
	    {
			if(!isset($type))
			{
				$modelid = 0;
				if(isset($pageid) && isset($page[$pageid]))
				{
					$modelid = $page[$pageid]['modelid'];
				}
			}
			$forward = '?module='.$module.'&action=manage';
		    include ('page_add.tpl.php');
		}
		break;

	case 'edit':
		global $page;
		$pageid = intval($pageid);
		if(!$pageid) showmessage($LANG['illegal_parameters']);
		if($pageid == $page['parentid']) showmessage('当前栏目不能与上级栏目相同');
		if($dosubmit)
		{
		    if(!$page['catname']) showmessage($LANG['page_name_not_null']);
			$page['catname'] = trim($page['catname']);
			$page['catdir'] = trim($page['catdir']);
			
			
			// 如果修改了目录名，删除以前的目录文件夹
			/*if($page['catdir'] != $page[$pageid]['catdir']){
				deldir(WWW_ROOT.$page[$pageid]['parentdir'].$page[$pageid]['catdir']); 
			}*/
		
			
			$cat->edit($pageid, $page, $setting);
			
			//以上设置是否应用到子栏目及信息,选择“是”权限、收费、扩展设置将应用到子栏目上，内容模板将应用到信息上。
			/*if($createtype_application && $page[$pageid]['child'])
			{
				$cat->update_child($pageid);
			}*/
			
			//$priv_group->update('pageid', $pageid, $priv_groupid);
			//$priv_role->update('pageid', $pageid, $priv_roleid);
	
			
			// 修复栏目数据 （增加）
			$cat->repair();
			
			// 更新栏目缓存 （增加）
			cache_common();
			cache_page();
			
			
			
			showmessage('操作成功！开始修复栏目数据...', '?module=page&action=repair'); 
		}
		else
	    {
			$page = $cat->get($pageid);
            @extract(new_htmlspecialchars($page));
			if($type == 1)
			{
				$priv_roleids = $priv_role->get_roleid('pageid', $pageid);
				$priv_roleids = implodeids($priv_roleids);
				//$priv_groupids = $priv_group->get_groupid('pageid', $pageid);
				//$priv_groupids = implodeids($priv_groupids);
			}
		    include ('page_edit.tpl.php');
		}
		break;

     case 'repair':

        $cat->repair();
        showmessage('栏目更新成功！开始更新栏目缓存 ...', '?module='.$module.'&action=updatecache');
		break;

     case 'delete':
		 //if(!array_key_exists($pageid, $page)) showmessage($LANG['illegal_parameters'], '?module=page&action=manage');
		 $cat->delete($pageid);
		 showmessage($LANG['operation_success'], '?module='.$module.'&action=updatecache&forward='.urlencode('?module=page&action=manage'));
		 break;

	case 'join':

	    if($dosubmit)
		{
			$targetpageid = intval($targetpageid);
			$sourcepageid = intval($sourcepageid);
			if(!$targetpageid || !$sourcepageid) showmessage('源栏目或目标栏目没有选择', $forward);
			if($targetpageid==$sourcepageid) showmessage($LANG['source_not_same_as_distinct_page'],$forward);

			$target = $cat->get($targetpageid);
			if($target['child']==1) showmessage($LANG['distinct_page_has_child_banned_add_information']);

			if($target['arrparentid'])
			{
				$arrparentid = explode(",", $r['arrparentid']);
				if(in_array($sourcepageid,$arrparentid)) showmessage($LANG['distinct_is_the_child_of_source_page_cannot_join']);
			}

			$source = $cat->get($sourcepageid);
			$cat->join($sourcepageid, $targetpageid);

		   showmessage($LANG['operation_success'], $forward);
		}
		else
		{
			foreach($page AS $pageid=>$c)
			{
				if($c['type']!=0) unset($page[$pageid]);
			}
			include 'page_join.tpl.php';
		}
		break;

    case 'listorder':
		$cat->listorder($listorder);
		showmessage($LANG['operation_success'], $forward);
        break;

	case 'recycle':
		$cat->recycle($pageid);
		showmessage($LANG['operation_success'], '?module='.$module.'&action=manage');
        break;
	case 'checkpage':
		if($page[$targetpageid]['modelid'] != $page[$sourcepageid]['modelid'])
		{
			echo -1;
		}
		elseif($page[$targetpageid]['child'])
		{
			echo -2;
		}
		elseif($targetpageid == $sourcepageid)
		{
			echo -3;
		}
		elseif(in_array($targetpageid,explode(',',$page[$sourcepageid]['arrchildid'])))
		{
			echo -4;
		}
        break;

	case 'updatecache':
		cache_common();
		cache_page();
		showmessage('更新成功', '?module=page&action=manage');
		break;

	case 'manage':
		
		$data = $cat->listinfo();
		$pages = array();
		foreach($data as $pageid => $page)
		{
			 $url = url($page['url']);
			 $type = $page['type'] == 0 ? '内部栏目' : ($page['type'] == 1 ? '<font color="blue">单网页</font>' : '<font color="red">外部链接</font>');
			 $model = $page['type'] == 0 ? '<a href="?module=model&action=model_field_manage&modelid='.$page['modelid'].'">'.$MODEL[$page['modelid']]['name'].'</a>' : '';
			 $add_child_cat = $page['type'] ? '<font color="#CCCCCC">'.$LANG['add_child_page'].'</font>' : "<a href='?module=$module&action=add&pageid=$pageid'>".$LANG['add_child_page']."</a>";
			 $pages[$page['pageid']] = array('id'=>$page['pageid'],'parentid'=>$page['parentid'],'name'=>str_replace(' ','&nbsp;',$page['catname']),'type'=>$type,'catdir'=>$catdir,'url'=>$url,'listorder'=>$page['listorder'],'model'=>$model,'style'=>$page['style'],'items'=>$page['items'],'hits'=>$page['hits'],'module'=>$module,'file'=>$file,'add_child_cat'=>$add_child_cat,'clear_cat'=>$clear_cat,'move_content'=>$move_content);
		}
		$str = "<tr>
					<td><input name='listorder[\$id]' type='text' size='3' value='\$listorder'></td>
					<td>\$id</td>
					<td>\$spacer<a href='?module=page&action=edit&pageid=\$id&parentid=\$parentid'><span class='\$style'>\$name</span></a></td>
					<td>\$type</td>
					<td>\$model</td>
					<td><a href='?module=content&action=manage&pageid=\$id' title='管理内容'>\$items</a></td>
					<td><a href='\$url' target='_blank'>访问</a></td>
					<td align='center'><a href='?module=page&action=edit&pageid=\$id&parentid=\$parentid'>修改</a> | <a href=javascript:confirmurl('?module=page&action=delete&pageid=\$id','确认删除{\$name}栏目吗？') >删除</a> | <a href='?module=content&action=manage&pageid=\$id'>内容</a></td>
				</tr>";
		$tree->tree($pages);
		$pages = $tree->get_tree(0, $str);
		
		include 'page_manage.tpl.php';
	
		break;
	/*case 'urlrule':
		$ishtml = intval($ishtml);
		$page_urlruleid = intval($page_urlruleid);
		echo form::select_urlrule('page', $ishtml, 'setting[page_urlruleid]', 'page_urlruleid', $page_urlruleid);
		break;*/
	case 'checkdir':
		if(!preg_match("/[a-zA-Z0-9_-]+$/i",$value)) exit('栏目目录名称只能为字母、数字、下划线，中划线');
		if($catdir == trim($value)) exit('success');
		foreach($page AS $k=>$v)
		{
			if($v['parentid'] == $parentid && $v['catdir'] == trim($value)) exit('栏目目录名称不能重复');
		}
		if($parentid == 0 && isset($MODULE[$value])) exit('栏目目录名称不能重复');
		exit('success');
		break;
	case 'checkname':
		if($catname == trim($value)) exit('success');
		foreach($page AS $k=>$v)
		{
			if($v['parentid'] == $parentid && $v['catname'] == trim($value)) exit('栏目名称不能重复');
		}
		exit('success');
		break;
    case 'more':
        if($dosubmit)
		{
            $page['catname'] = array_map("trim", $page['catname']);
			$page['catdir'] = array_map("trim",$page['catdir']);
            $c = $s = array();
            $c['type'] = $page['type'];
            $c['parentid'] = $page['parentid'];
            $c['modelid'] = $page['modelid'];

            $s['presentpoint'] = $setting['presentpoint'];
            $s['defaultchargepoint'] = $setting['defaultchargepoint'];
            $s['repeatchargedays'] = $setting['repeatchargedays'];
            $s['template_page'] = $setting['template_page'];
            $s['template_list'] = $setting['template_list'];
            $s['template_show'] = $setting['template_show'];
            $s['template_print'] = $setting['template_print'];
            foreach($page['catname'] AS $key => $value)
            {
                if(!empty($value) && !empty($page['catdir'][$key]))
                {
                    $c['catname'] = $page['catname'][$key];
                    $c['catdir'] = $page['catdir'][$key];
                    $c['ismenu'] = $page['ismenu'][$key];

                    $s['workflowid'] = $setting['workflowid'][$key];
                    $s['meta_title'] = $setting['meta_title'][$key];
                    $s['meta_keywords'] = $setting['meta_keywords'][$key];
                    $s['meta_description'] = $setting['meta_description'][$key];
                    $pageid = $cat->add($c, $s);
                    $priv_group->update('pageid', $pageid, $priv_groupid);
                    $priv_role->update('pageid', $pageid, $priv_roleid);
                    cache_common();
                }
                else
                {
                    unset($page['catname'][$key]);
                    unset($page['catdir'][$key]);
                    continue;
                }
            }
			if(!$pageid) showmessage('添加失败', '?module=page&action=more');
	        showmessage('添加成功', '?module=page&action=more');
		}
		else
	    {
			if(!isset($type))
			{
				$modelid = 0;
				if(isset($pageid) && isset($page[$pageid]))
				{
					$modelid = $page[$pageid]['modelid'];
				}
			}
		    include 'page_more.tpl.php';
		}
        break;
	case 'update_search':
		if($dosubmit)
		{
			if(!$count)
			{
				if(!isset($pageids) || $pageids[0] == 0) 
				{
					foreach($page as $cid=>$v)
					{
						if($v['type'] == 0) $pageids[] = $cid;
					}
				}
				foreach($pageids as $k=>$id)
				{
					if($page[$id]['type'] == 0 && $MODEL[$page[$id]['modelid']]['enablesearch'] && $page[$id]['child']==0)
					{
						$cids[] = $id;
					}
				}
				if($cids)
				{
					cache_write('search_page_'.$_userid.'.php', $cids);
					$count = count($cids);
					$forward = urlencode($forward);
					showmessage('开始遍历栏目...', "?module=$module&action=$action&forward=$forward&pagesize=$pagesize&dosubmit=1&count=$count");
				}
				else
				{
					showmessage('更新完成！', "?module=$module&action=$action");
				}
			}
			else
			{
				$pageids = cache_read('search_page_'.$_userid.'.php');
				$page = max(intval($page), 1);
				if($page == 1)
				{
				    $pageid = array_shift($pageids);
					cache_write('search_page_'.$_userid.'.php', $pageids);
                }
				$catname = $page[$pageid]['catname'];

				if($page[$pageid]['child']==0)
				{
					$offset = $pagesize*($page-1);
					if($page == 1)
					{
						$contents = cache_count("SELECT COUNT(*) AS `count` FROM `".DB_PRE."content` WHERE pageid=$pageid AND status=99");
						$total = $contents;
						$pages = ceil($total/$pagesize);
					}
					$max = min($offset+$pagesize, $total);
					for($i=$offset; $i<$max; $i++)
					{
						$c->update_search($pageid, $i);
					}
				}
				if($pages > $page)
				{
					$page++;
					$percent = round($max/$total, 2)*100;
					$message = "正在更新 <font color='blue'>$catname</font> 栏目中内容的全站搜索，共需更新 <font color='red'>$total</font> 篇内容<br />已更新 <font color='red'>{$max}</font> 篇内容（<font color='red'>{$percent}%</font>）";
					$forward = url_par("pageid=$pageid&page=$page&pages=$pages&total=$total");
				}
				elseif($pageids)
				{
					$message = "<font color='blue'>$catname</font> 栏目更新完成！";
					$forward = url_par("pageid=0&page=0&pages=0&total=0");
				}
				else
				{
					cache_delete('search_page_'.$_userid.'.php');
					$message = "更新完成！";
					$forward = '?module=page&action=update_search';
				}
				showmessage($message, $forward);
			}
		}
		else
		{
			include 'page_search.tpl.php';
		}
		break;
}
?>